package cn.heycm.blog.common.web.filter;

import cn.heycm.blog.common.entity.constant.Constant;
import cn.heycm.blog.common.entity.session.Session;
import cn.heycm.blog.common.entity.session.SessionContext;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 安全认证过滤器
 *
 * @author hey
 * @version 1.0
 * @since 2024/9/15 16:51
 */
@Component
public class AuthFilter extends OncePerRequestFilter implements Ordered {

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 1;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            setSession(request);
            checkAuth(request);
            filterChain.doFilter(request, response);
        } finally {
            removeSession();
        }
    }

    private void setSession(HttpServletRequest request) {
        String token = request.getHeader(Constant.TOKEN_KEY);
        if (!StringUtils.hasText(token)) {
            return;
        }
        Session session = new Session();
        SessionContext.set(session);
    }

    private void checkAuth(HttpServletRequest request) {
        String uri = request.getRequestURI();

        // TODO check auth permission
    }

    private void removeSession() {
        SessionContext.remove();
    }
}
